<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="学生姓名">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入学生姓名"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="listQuery.class" placeholder="请选择班级" clearable>
            <el-option label="一班" value="一班" />
            <el-option label="二班" value="二班" />
            <!-- 可以根据实际情况添加更多班级选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="listQuery.subject" placeholder="请选择学科" clearable>
            <el-option label="语文" value="语文" />
            <el-option label="数学" value="数学" />
            <!-- 可以根据实际情况添加更多学科选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="listQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="成绩范围">
          <el-input-number
            v-model="listQuery.minScore"
            placeholder="最低成绩"
            :min="0"
            :max="100"
          />
          <span> - </span>
          <el-input-number
            v-model="listQuery.maxScore"
            placeholder="最高成绩"
            :min="0"
            :max="100"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="exportData">导出数据</el-button>
          <el-button type="warning" @click="cleanData">清除异常数据</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
    >
      <el-table-column prop="name" label="学生姓名" />
      <el-table-column prop="class" label="班级" width="80" />
      <el-table-column prop="subject" label="学科" width="80" />
      <el-table-column prop="examScore" label="考试成绩" width="80" />
      <el-table-column prop="examDate" label="考试时间" width="120" />
      <el-table-column prop="status" label="学习状态" width="100">
        <template slot-scope="{row}">
          <!-- 修改部分 -->
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="weeklyStudyHours" label="每周学习总时长" width="120">
        <template slot-scope="{row}">
          {{ row.weeklyStudyHours ? row.weeklyStudyHours.reduce((sum, hours) => sum + hours, 0) : 0 }} 小时
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="age" label="年龄" width="60" />
      <el-table-column prop="attendanceRate" label="出勤率" width="80" />
      <el-table-column prop="homeworkCompletionRate" label="作业完成率" width="100" />
      <el-table-column prop="previousExamScore" label="上次考试成绩" width="120" />
      <!-- 新增操作列 -->
      <el-table-column label="操作" width="300">
        <template slot-scope="{row}">
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="handleRowClick(row)">详情</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showStudentProfile(row)">人物画像</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showInterestChange(row)">兴趣变化</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showKnowledgeShortcomings(row)">知识短板</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详细信息弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="学生详细信息">
      <div>
        <p>姓名: {{ selectedStudent.name }}</p>
        <p>班级: {{ selectedStudent.class }}</p>
        <p>学科: {{ selectedStudent.subject }}</p>
        <p>考试成绩: {{ selectedStudent.examScore }}</p>
        <p>考试时间: {{ selectedStudent.examDate }}</p>
        <p>学习状态: {{ selectedStudent.status }}</p>
        <p>每周学习总时长: {{ selectedStudent.weeklyStudyHours ? selectedStudent.weeklyStudyHours.reduce((sum, hours) => sum + hours, 0) : 0 }} 小时</p>        <p>性别: {{ selectedStudent.gender }}</p>
        <p>年龄: {{ selectedStudent.age }}</p>
        <p>出勤率: {{ selectedStudent.attendanceRate }}</p>
        <p>作业完成率: {{ selectedStudent.homeworkCompletionRate }}</p>
        <p>上次考试成绩: {{ selectedStudent.previousExamScore }}</p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 人物画像弹窗 -->
    <el-dialog :visible.sync="portraitDialogVisible" title="人物画像">
      <div>
        <div id="learning-style-radar" style="width: 600px; height: 400px;"></div>
      </div>
      <template #footer>
        <el-button @click="portraitDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 兴趣变化弹窗 -->
    <el-dialog :visible.sync="interestDialogVisible" title="兴趣变化">
      <div>
        <div id="interest-change-line-popup" style="width: 600px; height: 400px;"></div>
      </div>
      <template #footer>
        <el-button @click="interestDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 知识短板弹窗 -->
    <el-dialog :visible.sync="knowledgeDialogVisible" title="知识短板">
      <ul>
        <li v-for="shortcoming in selectedKnowledgeShortcomings" :key="shortcoming">{{ shortcoming }}</li>
      </ul>
      <template #footer>
        <el-button @click="knowledgeDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import mockData from './mockData.js'
import * as echarts from 'echarts' // 引入 ECharts 库

export default {
  name: 'ClassOverview',
  components: { Pagination },
  data() {
    return {
      // 模拟的数据库数据
      mockData,
      cleanedData: [], // 存储清洗后的数据
      list: [], // 当前显示的列表数据
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: undefined,
        dateRange: [],
        minScore: undefined,
        maxScore: undefined
      },
      totalStudents: 0,
      averageScore: 0,
      excellentStudents: 0,
      passingStudents: 0,
      dialogVisible: false,
      selectedStudent: {},
      portraitDialogVisible: false,
      portraitStudent: {},
      interestDialogVisible: false, // 新增兴趣变化弹窗显示状态
      interestStudent: {}, // 新增当前查看兴趣变化的学生数据
      knowledgeDialogVisible: false,
      selectedKnowledgeShortcomings: [],
      isDataCleaned: false // 标记数据是否已清洗
    }
  },
  created() {
    this.mockData.forEach(item => {
      // 生成随机的 weeklyStudyHours 数据
      const randomHours = []
      for (let i = 0; i < 12; i++) {
        // 生成 0 到 14 之间的随机整数
        const randomHour = Math.floor(Math.random() * 15)
        randomHours.push(randomHour)
      }
      this.$set(item, 'weeklyStudyHours', randomHours)
    })
    this.getList()
  },
  methods: {
    // 根据学习状态返回对应的标签类型
    getStatusTagType(status) {
      switch (status) {
        case '优秀':
          return 'success'
        case '良好':
          return 'warning'
        case '一般':
          return 'info'
        case '差':
          return 'danger'
        default:
          return 'info'
      }
    },
    // 清除异常数据
    cleanData() {
      this.listLoading = true
      setTimeout(() => {
        // 清洗数据
        this.cleanedData = this.mockData.filter(item => {
          // 检查关键字段是否存在且有效
          const hasValidScore = item.examScore !== null && !isNaN(item.examScore) && item.examScore >= 0 && item.examScore <= 100
          const hasValidPreviousScore = item.previousExamScore === null || (!isNaN(item.previousExamScore) && item.previousExamScore >= 0 && item.previousExamScore <= 100)
          const hasValidAttendance = item.attendanceRate !== null
          const hasValidHomework = item.homeworkCompletionRate !== null
          const hasValidWeeklyHours = Array.isArray(item.weeklyStudyHours) && item.weeklyStudyHours.every(hour => !isNaN(hour) && hour >= 0)

          return hasValidScore && hasValidPreviousScore && hasValidAttendance && hasValidHomework && hasValidWeeklyHours
        })

        this.isDataCleaned = true
        this.$message({
          message: `数据清洗完成，共清除 ${this.mockData.length - this.cleanedData.length} 条异常数据`,
          type: 'success'
        })

        // 重新获取列表数据
        this.getList()
        this.listLoading = false
      }, 2500)
    },
    // 获取列表数据
    getList() {
      this.listLoading = true
      setTimeout(() => {
        // 1. 根据查询条件过滤数据
        let result = this.isDataCleaned ? [...this.cleanedData] : [...this.mockData]

        const { name, class: className, subject, dateRange, minScore, maxScore } = this.listQuery

        if (name) {
          result = result.filter(item => item.name.includes(name))
        }

        if (className) {
          result = result.filter(item => item.class === className)
        }

        if (subject) {
          result = result.filter(item => item.subject === subject)
        }

        if (dateRange && dateRange.length === 2) {
          const [startDate, endDate] = dateRange
          result = result.filter(item => {
            const examDate = new Date(item.examDate)
            return examDate >= new Date(startDate) && examDate <= new Date(endDate)
          })
        }

        if (minScore) {
          result = result.filter(item => item.examScore >= minScore)
        }

        if (maxScore) {
          result = result.filter(item => item.examScore <= maxScore)
        }

        // 2. 更新总数
        this.total = result.length
        this.totalStudents = result.length

        // 3. 计算统计信息
        if (result.length > 0) {
          const validScores = result.filter(item => item.examScore !== null)
          const totalScore = validScores.reduce((sum, item) => sum + item.examScore, 0)
          this.averageScore = validScores.length > 0 ? totalScore / validScores.length : 0
          this.excellentStudents = validScores.filter(item => item.examScore >= 90).length
          this.passingStudents = validScores.filter(item => item.examScore >= 60).length
        } else {
          this.averageScore = 0
          this.excellentStudents = 0
          this.passingStudents = 0
        }

        // 4. 分页处理
        const { page, limit } = this.listQuery
        const start = (page - 1) * limit
        const end = page * limit

        // 5. 设置当前页数据
        this.list = result.slice(start, end)

        this.listLoading = false
      }, 500)
    },
    showStudentProfile(row) {
      this.portraitDialogVisible = true
      // 使用 $nextTick 确保 DOM 更新后再绘制图表
      this.$nextTick(() => {
        this.drawLearningStyleRadar(row)
      })
    },
    drawLearningStyleRadar(row) {
      const learningStyle = row.learningStyle
      const radarChart = echarts.init(document.getElementById('learning-style-radar'))
      const radarOption = {
        title: {
          text: '学习风格雷达图',
          left: 'center'
        },
        radar: {
          indicator: [
            { name: '语言智能', max: 10 },
            { name: '逻辑智能', max: 10 },
            { name: '空间智能', max: 10 },
            { name: '音乐智能', max: 10 },
            { name: '身体运动智能', max: 10 },
            { name: '人际智能', max: 10 },
            { name: '内省智能', max: 10 }
          ]
        },
        series: [
          {
            type: 'radar',
            data: [
              {
                value: [
                  learningStyle.language,
                  learningStyle.logic,
                  learningStyle.spatial,
                  learningStyle.musical,
                  learningStyle.bodily,
                  learningStyle.interpersonal,
                  learningStyle.intrapersonal
                ],
                name: '学习风格'
              }
            ]
          }
        ]
      }
      radarChart.setOption(radarOption)
    },
    // 显示兴趣变化
    showInterestChange(row) {
      this.interestDialogVisible = true
      this.$nextTick(() => {
        this.drawInterestChangeLine(row) // 绘制兴趣变化折线图
      })
    },
    drawInterestChangeLine(row) {
      const interestChange = row.interestChange
      // 修改为正确的 DOM 元素 ID
      const interestChart = echarts.init(document.getElementById('interest-change-line-popup'))
      const interestOption = {
        title: {
          text: '兴趣变化折线图',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['第1阶段', '第2阶段', '第3阶段', '第4阶段', '第5阶段']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '数学',
            type: 'line',
            data: interestChange.math
          },
          {
            name: '英语',
            type: 'line',
            data: interestChange.english
          },
          {
            name: '语文',
            type: 'line',
            data: interestChange.chinese
          }
        ]
      }
      interestChart.setOption(interestOption)
    },
    // 显示知识短板弹窗
    showKnowledgeShortcomings(row) {
      console.log('row :>> ', row)
      this.selectedKnowledgeShortcomings = row.knowledgeShortcomings
      console.log('this.selectedKnowledgeShortcomings :>> ', this.selectedKnowledgeShortcomings)
      this.knowledgeDialogVisible = true
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    // 重置查询
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: undefined,
        dateRange: [],
        minScore: undefined,
        maxScore: undefined
      }
      this.isDataCleaned = false // 重置数据清洗状态
      this.getList()
    },

    // 导出数据
    exportData() {
      const ws = XLSX.utils.json_to_sheet(this.list)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'class_overview.xlsx')
    },

    // 处理表格行点击事件
    handleRowClick(row) {
      console.log(row)
      this.selectedStudent = { ...row }
      this.dialogVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;

  .el-form-item {
    margin-bottom: 10px;
  }
}

.statistics-container {
  padding-bottom: 10px;
}

.chart-container {
  padding-bottom: 10px;
}
</style>
